#undef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <windowsx.h>
#include <ddraw.h>
#include "ddutil.h"

extern "C" IDirectDrawSurface* DDLoadBitmap(IDirectDraw *pdd, LPCSTR szBitmap, int dx, int dy)
{
	HBITMAP hbm;
	BITMAP	bm;
	DDSURFACEDESC ddsd;
	IDirectDrawSurface *pdds;
	
	hbm = (HBITMAP)LoadImage(GetModuleHandle(NULL), szBitmap, IMAGE_BITMAP, dx, dy,
		LR_CREATEDIBSECTION);
	if (hbm == NULL)
		hbm = (HBITMAP)LoadImage(NULL, szBitmap, IMAGE_BITMAP, dx, dy,
			LR_LOADFROMFILE | LR_CREATEDIBSECTION);
	
	if (hbm == NULL)
		return NULL;
		
	GetObject(hbm, sizeof(bm), &bm);
	
	ZeroMemory(&ddsd, sizeof(ddsd));
	ddsd.dwSize = sizeof(ddsd);
	ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
	ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
	ddsd.dwWidth = bm.bmWidth;
	ddsd.dwHeight = bm.bmHeight;
	
	if (pdd->CreateSurface(&ddsd, &pdds, NULL) != DD_OK)
		return NULL;
		
	DDCopyBitmap(pdds, hbm, 0, 0, 0, 0);
	
	DeleteObject(hbm);
	
	return pdds;
}

HRESULT DDReLoadBitmap(IDirectDrawSurface* pdds, LPCSTR szBitmap)
{
	HBITMAP hbm;
	HRESULT hr;
	hbm = (HBITMAP)LoadImage(GetModuleHandle(NULL), szBitmap, IMAGE_BITMAP, 0, 0,
			LR_CREATEDIBSECTION);
	if (hbm == NULL)
		hbm = (HBITMAP)LoadImage(NULL, szBitmap, IMAGE_BITMAP, 0, 0,
				LR_LOADFROMFILE | LR_CREATEDIBSECTION);
	if (hbm == NULL)
	{
		char str[128];
		sprintf(str, "handle is null [%s]\n", szBitmap);
		OutputDebugString(str);
		return E_FAIL;
	}
	hr = DDCopyBitmap(pdds, hbm, 0, 0, 0, 0);
	if (hr != DD_OK)
	{
		OutputDebugString("ddcopybitmap failed\n");
	}
	
	DeleteObject(hbm);
	return hr;
}

extern "C" HRESULT DDCopyBitmap(IDirectDrawSurface* pdds, HBITMAP hbm, int x, int y, int dx, int dy)
{
	HDC hdcImage;
	HDC hdc;
	BITMAP bm;
	DDSURFACEDESC ddsd;
	HRESULT hr;
	
	if (hbm == NULL || pdds == NULL)
		return E_FAIL;
	
	pdds->Restore();
	hdcImage = CreateCompatibleDC(NULL);
	if (!hdcImage)
		OutputDebugString("createcompatible dc failed\n");
	SelectObject(hdcImage, hbm);
	GetObject(hbm, sizeof(bm), &bm);
	dx = dx == 0 ? bm.bmWidth : dx;
	dy = dy == 0 ? bm.bmHeight : dy;
	ddsd.dwSize = sizeof(ddsd);
	ddsd.dwFlags = DDSD_HEIGHT | DDSD_WIDTH;
    pdds->GetSurfaceDesc(&ddsd);
	
	if ((hr = pdds->GetDC(&hdc)) == DD_OK)
	{
		StretchBlt(hdc, 0, 0, ddsd.dwWidth, ddsd.dwHeight, hdcImage, x, y, dx, dy, SRCCOPY);
		pdds->ReleaseDC(hdc);
	}
	
	DeleteDC(hdcImage);
	
	return hr;
}

extern "C" IDirectDrawPalette* DDLoadPalette(IDirectDraw* pdd, LPCSTR szBitmap)
{
	IDirectDrawPalette* ddpal;
	int i;
	int n;
	int fh;
	HRSRC h;
	LPBITMAPINFOHEADER lpbi;
	PALETTEENTRY ape[256];
	RGBQUAD* prgb;
	for (i = 0; i < 256; i++)
	{
		ape[i].peRed   = (BYTE)(((i >> 5) & 0x07) * 255 / 7);
        ape[i].peGreen = (BYTE)(((i >> 2) & 0x07) * 255 / 7);
        ape[i].peBlue  = (BYTE)(((i >> 0) & 0x03) * 255 / 3);
		ape[i].peFlags = (BYTE)0;
	}
	
	
}
